package xx.iverson.school_manage.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xx.iverson.school_manage.entity.Points;
import xx.iverson.school_manage.log.Loggable;
import xx.iverson.school_manage.mapper.PointsMapper;
import xx.iverson.school_manage.service.PointsService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wei77
 */
@Service
public class PointsServiceImpl implements PointsService {

    @Resource
    private PointsMapper pointsMapper;

    @Override
    @Loggable(value = "获取用户积分")
    public Integer getPoints(Integer userId) {
        return pointsMapper.selectPoints(userId);
    }

    @Override
    @Loggable(value = "获取积分列表")
    public List<Points> getListPoints(Integer number) {
        if (number==0){
            return pointsMapper.selectAllPoints();
        }
        return pointsMapper.selectListPoints(number);
    }

    @Override
    public List<Points> getLikePoints(String name) {
        return pointsMapper.selectLikePoints(name);
    }

    @Override
    public List<Points> getLetterPoints(String letter) {
        return pointsMapper.selectLetterPoints(letter);
    }

    @Transactional
    @Override
    @Loggable(value = "重置积分")
    public boolean resetPoints() {
        return pointsMapper.insertResetPoints() && pointsMapper.updatePoints();
    }

    @Transactional
    @Override
    @Loggable(value = "重置积分为0")
    public boolean resetPointsZero() {
        return pointsMapper.insertResetPointsZero() && pointsMapper.updatePointsZero();
    }

    @Override
    public Integer getRank(Integer userId) {
        // 查询排名
        return pointsMapper.getRank(userId);
    }

    @Override
    @Loggable(value = "获取积分分布")
    public Map<String, Integer> getPointsDistribution() {
        Map<String, Integer> distribution = new HashMap<>();
        int above90 = 0, eightyToNinety = 0, sixtyToEighty = 0, belowSixty = 0;

        List<Points> points = pointsMapper.selectAllPoints();
        for (Points point : points) {
            if (point.getPoints() >= 90) {
                above90++;
            } else if (point.getPoints() >= 80) {
                eightyToNinety++;
            } else if (point.getPoints() >= 60) {
                sixtyToEighty++;
            } else {
                belowSixty++;
            }
        }

        distribution.put("大于90分", above90);
        distribution.put("80分-90分", eightyToNinety);
        distribution.put("60分-80分", sixtyToEighty);
        distribution.put("小于60分", belowSixty);

        return distribution;
    }
}